﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebStore.Domain.Entities;
using WebStore.Domain.Entities.Model;
using WebStore.Infrastructure.Service.Interface;

namespace WebStore.Infrastructure.Service.Implementation
{
    public class AccountService:IAccountService
    {
        private readonly Entities _entities;

        public AccountService(Entities entities)
        {
            _entities = entities;
        }

        public bool LogOn(string email, string password, out string errorMessage)
        {
            errorMessage = null;
            if (_entities.Users.Any(x => x.Email == email && x.Password == password))
                return true;
            errorMessage = "Email or password is incorect";
            return false;
        }

        public bool Register(string email, string password, out string errorMessage)
        {
            errorMessage = null;
            if(_entities.Users.Any(x=>x.Email==email))
            {
                errorMessage = "Email exisitng in database";
                return false;
            }
            _entities.Users.Add(new User
                                    {
                                        Email = email,
                                        Password = password
                                    });
            _entities.SaveChanges();
            return true;
        }

        public bool Update(string email,string firstName, string secondName, string lastName, string addressLine, string city, string postalCode)
        {
            var user = _entities.Users.FirstOrDefault(x => x.Email == email);
            user.FirstName = firstName;
            user.SecondName = secondName;
            user.LastName = lastName;
            user.AddressLine = addressLine;
            user.City = city;
            user.PostalCode = postalCode;
            _entities.SaveChanges();
            return true;
        }
    }

}
